package cn.jdemo.juc.threadPool;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 阻塞系数(BlockingCoefficient) = 阻塞时间 / (阻塞时间 + cpu时间)
 *
 * 线程池线程数量 =  Runtime.getRuntime().availableProcessors() / (1-阻塞系数)
 *
 * 须知:
 *  计算密集型任务，阻塞时间较小，近0，故阻塞系数接近于0
 *  io密集型任务，阻塞时间较大，故阻塞时间近1
 *
 * @description
 * @date 2020/12/14
 */
public class BlockingCoefficientOfThreadPool {

    public static void main(String[] args) throws InterruptedException {
        test01();
    }

    /**
     * 返回结果:
     * 返回正在主动执行任务的线程的大概数量:0
     * 返回正在主动执行任务的线程的大概数量:1
     * pool-1-thread-1
     * ... ...
     */
    public static void test01() throws InterruptedException {
        // 阻塞系数
        float blockingCoefficient = 0.1f;
        ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool((int) (Runtime.getRuntime().availableProcessors() / (1 - blockingCoefficient)),
                Executors.defaultThreadFactory());
        System.out.println("返回正在主动执行任务的线程的大概数量:"+executorService.getActiveCount());
        executorService.submit(() -> {
            try {
                Thread.sleep(2000l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        });
        Thread.sleep(1000l);
        System.out.println("返回正在主动执行任务的线程的大概数量:"+executorService.getActiveCount());
        // executorService.shutdown();
        executorService.shutdownNow();
        System.out.println("关闭");
    }

}
